<template>
    <!-- 头部 搜索、新增 区域 -->
    <el-row :gutter="20" class="header">
        <el-col :span="6">
            <el-input v-model="search" placeholder="请输入房屋名称" clearable>
                <template #append>
                    <el-button @click="getHouseByTenantId"> 搜索 </el-button>
                </template>
            </el-input>
        </el-col>
        <el-col :span="6">
            <el-button type="primary" @click="getRentable()">新增租房</el-button>
        </el-col>
    </el-row>

    <!-- 华丽的分割线 -->
    <el-divider />

    <!-- 表格形式展示当前租户下的房屋数据 -->
    <div>
        <el-table :data="houseData" row-key="id" style="width: 100%">
            <el-table-column prop="id" label="编号" v-if="false" />
            <el-table-column prop="path" label="路径" width="250" sortable/>
            <el-table-column prop="name" label="房产名称" width="120" />
            <el-table-column prop="typeName" label="房产类型" width="110" sortable/>
            <el-table-column prop="statusName" label="房产状态" width="110" sortable/>
            <el-table-column prop="area" label="房产面积" width="110" sortable/>

            <el-table-column prop="tenantName" label="租用人" v-if="false" />
            <el-table-column prop="startDate" label="开始租用时间" v-if="false" sortable/>
            <!-- 固定字段 -->
            <el-table-column fixed="right" label="操作" width="200">

                <template #="rs">
                    <el-button link type="primary" size="small"
                        @click="editDialog = true; currentHouseId = rs.row.id; getHouseStatus()">调整</el-button>

                    <!-- 确认框 -->
                    <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消"
                        @confirm="stopRentHouse(rs.row.id)" icon-color="#F56C6C" title="确认停租这个房屋？">
                        <template #reference>
                            <el-button link type="primary" size="small">停租</el-button>
                        </template>
                    </el-popconfirm>
                </template>

            </el-table-column>
        </el-table>
    </div>

    <!-- 底部分页器 -->
    <div v-if="total > 0">
        <div class="page-box">
            <div class="pagination-block">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :small="true" :disabled="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getHouseByTenantId"
                    @current-change="getHouseByTenantId" />
            </div>
        </div>
    </div>

    <!-- 弹出层 -->
    <!-- 新增租房的弹出层 -->
    <el-dialog v-model="newTenantDialog" title="新增租房" width="55%">

        <el-row :gutter="20" class="header">
            <el-col :span="8">
                <el-input v-model="searchRentable" placeholder="请输入房屋名称" clearable>
                    <template #append>
                        <el-button @click="getRentableData"> 搜索 </el-button>
                    </template>
                </el-input>
            </el-col>
        </el-row>

        <el-divider />
        <!-- 表格形式展示可租用房屋 -->
        <el-table :data="rentableData" row-key="id" style="width: 100%" max-height="250">
            <el-table-column prop="id" label="编号" v-if="false" />
            <el-table-column prop="path" label="房屋位置" width="200" sortable/>
            <el-table-column prop="name" label="房产名称" width="120" v-if="false" />
            <el-table-column prop="typeName" label="房产类型" width="110" sortable/>
            <el-table-column prop="statusName" label="房产状态" width="110" sortable/>
            <el-table-column prop="area" label="房产面积" width="110" sortable/>
            <!-- 隐藏字段 -->
            <el-table-column prop="isLastLevel" label="是否为最后一层" v-if="false" />
            <!-- 固定字段 -->
            <el-table-column fixed="right" label="操作" width="100">

                <template #="rs">

                    <!-- 确认框 -->
                    <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消"
                        @confirm="rentHouse(rs.row.id)" icon-color="#7EBE53" title="确认租用这个房屋？">
                        <template #reference>
                            <el-button link type="primary" size="small">租用</el-button>
                        </template>
                    </el-popconfirm>
                </template>

            </el-table-column>
        </el-table>
        <!-- 底部分页器 -->
        <div v-if="totalRentable > 0">
            <div class="page-box">
                <div class="pagination-block">
                    <el-pagination v-model:current-page="currentPageRentable" v-model:page-size="pageSizeRentable"
                        :page-sizes="[10, 20, 50, 100]" :small="true" :disabled="false" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalRentable"
                        @size-change="getRentableData" @current-change="getRentableData" />
                </div>
            </div>
        </div>
    </el-dialog>

    <!-- 调整租房的弹出层 -->
    <el-dialog v-model="editDialog" title="调整租房" width="30%">
        <el-form>
            <el-select v-model="houseStatusId" placeholder="请选择房屋状态">
                <el-option v-for="item in houseStatusData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button type="primary" @click="changeHouseStatus" style="margin-left: 20px;">确定</el-button>
        </el-form>
    </el-dialog>
</template>



<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

import { useRouter } from 'vue-router';
const router = useRouter();

import { useUserInfoStore } from '@/stores/userInfo.js';
const userInfoStore = useUserInfoStore();
const userInfo = userInfoStore.userInfo;

import { houseGetStatusService } from '@/api/property.js'
import { tenantGetHouseService, tenantGetRentabelHouseService, tenantRentService, tenantStopRentService, tenantChangeHouseStatusService } from '@/api/user.js'

// 初始化参数
// 按名称模糊搜索、分页
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchRentable = ref('')
const currentPageRentable = ref(1)
const pageSizeRentable = ref(10)
const totalRentable = ref(0)

const houseStatusData = ref([])
const houseStatusId = ref()
const currentHouseId = ref('')

// 房屋信息列表
let houseData = ref([])
let rentableData = ref([])
// 新增、调整租房弹出窗显示标志
let newTenantDialog = ref(false)
let editDialog = ref(false)
// 获取当前租户下的房屋信息
async function getHouseByTenantId() {
    try {
        let result = await tenantGetHouseService(userInfo.id, search.value, currentPage.value, pageSize.value)
        if (result.code == 200) {
            houseData.value = result.data.list;
            total.value = result.data.total;
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.warning(result.msg)
            houseData.value = []
        }
    } catch (error) {
        ElMessage.error('系统异常 (getHouseByTenantId)')
    }
}
getHouseByTenantId();

// 获取当前可租房屋信息
async function getRentableData() {
    try {
        let result = await tenantGetRentabelHouseService(searchRentable.value, currentPageRentable.value, pageSizeRentable.value)
        if (result.code == 200) {
            rentableData.value = result.data.list;
            totalRentable.value = result.data.total;
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
            rentableData.value = []
        }
    } catch (error) {
        ElMessage.error('系统异常 (getRentableData)')
    }
}
let getRentable = () => {
    getRentableData()
    newTenantDialog.value = true
}

// 租户新租房屋
async function rentHouse(houseId) {
    try {
        let result = await tenantRentService(userInfo.id, houseId)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getHouseByTenantId()
            getRentableData()
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (rentHouse)')
        getHouseByTenantId()
    }
}
// 租户停租房屋
async function stopRentHouse(houseId) {
    try {
        let result = await tenantStopRentService(houseId)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getHouseByTenantId()
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (stopRentHouse)')
        getHouseByTenantId()
    }
}

// 获取房屋状态列表
async function getHouseStatus() {
    try {
        let result = await houseGetStatusService()
        if (result.code == 200) {
            houseStatusData.value = result.data;
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常')
    }
}
// 调整房屋状态
async function changeHouseStatus() {
    try {
        let result = await tenantChangeHouseStatusService(currentHouseId.value, houseStatusId.value)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getHouseByTenantId()
            editDialog.value = false
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
    } catch (error) {
        ElMessage.error('系统异常 (changeHouseStatus)')
    }
}

</script>

<style>
.header {
    margin-bottom: 7px;
}
</style>